package com.itdct.onflow.core.util

import cn.hutool.crypto.SecureUtil
import cn.hutool.crypto.asymmetric.KeyType
import com.itdct.onflow.core.config.OnflowConfig
import org.springframework.stereotype.Component

/**
 * @author Zhouwx
 * @date 2025/8/22 13:58:23
 * @version 1.0
 * @description
 */
@Component
class ProjectRsaUtil(
    val onflowConfig: OnflowConfig
) {
    val rsa = SecureUtil.rsa(onflowConfig.privateKey, onflowConfig.publicKey)
    fun getPublicKey(): String = onflowConfig.publicKey

    fun getPrivateKey(): String = onflowConfig.privateKey

    fun publicKeyEncrypt(data: String): String {
        return rsa.encryptBase64(data, KeyType.PublicKey)
    }

    fun privateKeyDecrypt(data: String): String {
        try {
            return rsa.decryptStr(data, KeyType.PrivateKey)
        } catch (e: Exception) {
            throw RuntimeException("RSA解密失败")
//            logWarn("RSA解密失败", e)
//            return null
        }
    }

    companion object {
        fun generateRsaKeys(): Pair<String, String> {
            val rsa = SecureUtil.rsa()
            return Pair(rsa.publicKeyBase64, rsa.privateKeyBase64)
        }
    }
}

fun main() {
    val (publicKey, privateKey) = ProjectRsaUtil.generateRsaKeys()
    println("publicKey: $publicKey")
    println("privateKey: $privateKey")
}